package com.itwlj.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itwlj.constant.MessageConstant;
import com.itwlj.dto.GoodsDTO;
import com.itwlj.dto.GoodsPageQueryDTO;
import com.itwlj.entity.Category;
import com.itwlj.entity.Comment;
import com.itwlj.entity.Goods;
import com.itwlj.entity.SubCategory;
import com.itwlj.exception.DeletionNotAllowedException;
import com.itwlj.mapper.GoodsMapper;
import com.itwlj.mapper.GoodsSpecLinksMapper;
import com.itwlj.mapper.SubCategoryMapper;
import com.itwlj.result.PageResult;
import com.itwlj.service.CategoryService;
import com.itwlj.service.GoodsService;
import com.itwlj.service.SkuService;
import com.itwlj.service.SpecService;
import com.itwlj.vo.GoodsDetailVO;
import com.itwlj.vo.GoodsVO;
import com.itwlj.vo.SkuVO;
import com.itwlj.vo.SpecVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 商品业务层
 */
@Service
public class GoodsServiceImpl implements GoodsService {

    @Autowired
    private GoodsMapper goodsMapper;
    @Autowired
    private GoodsSpecLinksMapper goodsSpecLinksMapper;
    @Autowired
    private SpecService specService;
    @Autowired
    private SkuService skuService;
    @Autowired
    private SubCategoryMapper subCategoryMapper;
    @Autowired
    private CategoryService categoryService;

    /**
     * 新增商品
     *
     * @param goodsDTO
     */
    @Transactional
    public void insert(GoodsDTO goodsDTO) {
        Goods goods = new Goods();
        BeanUtils.copyProperties(goodsDTO, goods);
        goodsMapper.insert(goods);

        List<Long> specsIds = goodsDTO.getSpecIds();
        for (Long specsId : specsIds) {
            goodsSpecLinksMapper.insert(goods.getId(), specsId);
        }
    }

    /**
     * 商品分页查询
     *
     * @param goodsPageQueryDTO
     * @return
     */
    public PageResult pageQuery(GoodsPageQueryDTO goodsPageQueryDTO) {
        PageHelper.startPage(goodsPageQueryDTO.getPage(), goodsPageQueryDTO.getPageSize());

        Page<GoodsVO> page = goodsMapper.pageQuery(goodsPageQueryDTO);
        List<GoodsVO> records = page.getResult();

        records.forEach(goodsVO -> {
            List<SpecVO> specVOList = specService.getByGoodsId(goodsVO.getId());
            goodsVO.setSpecList(specVOList);
        });

        return new PageResult(page.getTotal(), records);
    }

    /**
     * 商品批量删除
     *
     * @param ids
     */
    @Transactional
    public void deleteBatch(List<Long> ids) {
        for (Long id : ids) {
            List<SkuVO> skuVOList = skuService.getByGoodsId(id);
            if (!skuVOList.isEmpty()) {
                throw new DeletionNotAllowedException(MessageConstant.GOODS_BE_RELATED_BY_SKU);
            }

            goodsMapper.deleteBatch(ids);
            goodsSpecLinksMapper.deleteByGoodsIds(ids);
        }

    }

    /**
     * 根据id修改商品
     *
     * @param goodsDTO
     */
    public void update(GoodsDTO goodsDTO) {
        Goods goods = new Goods();
        BeanUtils.copyProperties(goodsDTO, goods);
        goodsMapper.update(goods);
    }

    /**
     * 商品起售停售
     *
     * @param status
     * @param id
     */
    public void startOrStop(Integer status, Long id) {
        Goods goods = Goods.builder()
                .id(id)
                .status(status)
                .build();

        goodsMapper.update(goods);
    }

    /**
     * 根据子分类id查询商品
     *
     * @param subCategoryId
     * @return
     */
    public List<Goods> getBySubCategoryId(Long subCategoryId) {
        List<Goods> goodsList = goodsMapper.getBySubCategoryId(subCategoryId);
        return goodsList;
    }

    /**
     * 根据关键词搜索商品
     *
     * @param keyword
     * @return
     */
    public List<Goods> search(String keyword) {
        return goodsMapper.getByNameLike(keyword);
    }

    /**
     * 根据id查询商品
     *
     * @param id
     * @return
     */
    public GoodsDetailVO getById(Long id) {
        Goods goods = goodsMapper.getById(id);
        GoodsDetailVO goodsDetailVO = new GoodsDetailVO();
        BeanUtils.copyProperties(goods, goodsDetailVO);

        //获取当前商品所属分类
        SubCategory subCategory = subCategoryMapper.getById(goodsDetailVO.getSubCategoryId());
        Category category = categoryService.getById(subCategory.getCategoryId());

        //获取规格
        List<SpecVO> specVOList = specService.getByGoodsId(goodsDetailVO.getId());

        //获取当前商品图片信息
        List<SkuVO> skuVOList = skuService.getByGoodsId(id);
        List<String> pictures = new ArrayList<>();
        pictures.add(goodsDetailVO.getPicture());

        int maxPictures = 5;
        for (SkuVO skuVO : skuVOList) {
            if (pictures.size() >= maxPictures) {
                break;
            }
            pictures.add(skuVO.getPicture());
        }

        //获取当前商品评论信息
        List<Comment> commentList = goodsMapper.getCommentByGoodsId(id);
        Integer totalRating = 0;
        Integer rating = 0;
        if (!commentList.isEmpty()){
            for (Comment comment : commentList){
                totalRating += comment.getRating();
            }
            rating = totalRating == 0 ? 0 : totalRating/commentList.size();
        }

        //封装商品信息
        goodsDetailVO.setCategoryId(category.getId());
        goodsDetailVO.setCategoryName(category.getName());
        goodsDetailVO.setSubCategoryId(subCategory.getId());
        goodsDetailVO.setSubCategoryName(subCategory.getName());
        goodsDetailVO.setMainPictures(pictures);
        goodsDetailVO.setSpecList(specVOList);
        goodsDetailVO.setSkuList(skuVOList);
        goodsDetailVO.setRating(rating);
        goodsDetailVO.setCommentList(commentList);

        return goodsDetailVO;
    }
}
